
package com.example.androidproject.file;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import java.io.File;
import java.util.List;
import com.example.androidproject.R;
import com.example.androidproject.chat.ChatAdapter;
import com.example.androidproject.databinding.FragmentFileBinding;
import com.example.androidproject.sqlite.FileRepository;

public class FileFragment extends Fragment{
    private FragmentFileBinding binding;
    private FileRepository fileRepository;
    private FileAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentFileBinding.inflate(inflater, container, false);

        fileRepository = new FileRepository(binding.getRoot().getContext());
        List<FileRepository.FileRecord> allFiles = fileRepository.getAllFiles();
        Log.e("???", "allFiles: " + allFiles);
        adapter = new FileAdapter(allFiles, new FileAdapter.ItemClickListener() {
            @Override
            public void itemClickEvent(FileRepository.FileRecord fileRecord) {
                showFileDetails(fileRecord);
            }
        });
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));

        return binding.getRoot();
    }

    private void openFile(FileRepository.FileRecord fileRecord) {
        // 获取缓存目录并构造文件路径
        File cacheDir = requireContext().getCacheDir();
        File file = new File(cacheDir, fileRecord.getFileName());

        // 检查文件是否存在
        if (!file.exists()) {
            Log.e("FileFragment", "File does not exist: " + file.getAbsolutePath());
            return;
        }

        // 获取文件 URI
        Uri fileUri = FileProvider.getUriForFile(requireContext(), "com.example.androidproject.fileprovider", file);

        // 确保 Intent 使用正确的 MIME 类型
        Intent openIntent = new Intent(Intent.ACTION_VIEW);
        openIntent.setDataAndType(fileUri, getMimeType(file.getAbsolutePath()));
        openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        try {
            startActivity(openIntent);
        } catch (ActivityNotFoundException e) {
            Log.e("FileFragment", "No application can handle this file", e);
        }
    }

    // 辅助方法获取 MIME 类型
    private String getMimeType(String filePath) {
        String mimeType = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
        if (extension != null) {
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return mimeType != null ? mimeType : "application/octet-stream";
    }



    private void showFileDetails(FileRepository.FileRecord fileRecord) {
        View detailsContainer = binding.fileDetailsContainer;
        detailsContainer.setVisibility(View.VISIBLE);

        TextView fileNameTextView = binding.fileName;
        TextView senderIdTextView = binding.senderId;
        TextView dateTextView = binding.fileDate;


        fileNameTextView.setText(fileRecord.getFileName());
        senderIdTextView.setText(fileRecord.getSender());
        dateTextView.setText(String.valueOf(fileRecord.getTimestamp()));

        Button deleteButton = binding.deleteButton;
//        Button shareButton = binding.shareButton;
        Button openButton = binding.openButton;

        deleteButton.setOnClickListener(v -> deleteChat(fileRecord.getId()));
//        shareButton.setOnClickListener(v -> shareChat(fileRecord));
        openButton.setOnClickListener(v -> openFile(fileRecord));

    }

    private void deleteChat(int id) {
        adapter.deleteById(id);
    }

//    public void shareChat(FileRepository.FileRecord fileRecord) {
//        Intent shareIntent = new Intent(Intent.ACTION_SEND);
//        shareIntent.setType("text/plain");
//        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Chat File");
//        shareIntent.putExtra(Intent.EXTRA_TEXT, "File: " + fileRecord.getFileName() + "\nSender: " + fileRecord.getSender() + "\nDate: " + fileRecord.getTimestamp());
//        startActivity(Intent.createChooser(shareIntent, "Share via"));
//    }
}
